package wechat

import (
	"gitee.com/edodo/flysdk/api"
)

func init() {
	api.RegisterBaseMpApi(api.QQ, &wcMpApi{})
}

type wcMpApi struct {
}

// https://developers.weixin.qq.com/miniprogram/dev/OpenApiDoc/mp-access-token/getAccessToken.html
func (wcApi *wcMpApi) GetAccessToken(config *api.MpConfig) (at *api.AccessToken, e error) {
	// get access token by http request
	p := map[string]string{
		"grant_type": "client_credential",
		"appid":      config.AppId,
		"secret":     config.AppSecret,
	}
	output := new(WxAccessToken)
	if e = api.Get(ACCESS_TOKEN_URL, p, output); e != nil {
		//glog.Errorf("Get access token failed: %v", e)
		return
	}
	at, e = output.ToAccessToken()
	return
}

// https://developers.weixin.qq.com/miniprogram/dev/OpenApiDoc/mp-access-token/getStableAccessToken.html
func (wcApi *wcMpApi) GetStableAccessToken(config *api.MpConfig, force bool) (at *api.AccessToken, e error) {
	if !force {
		return wcApi.GetAccessToken(config)
	}
	// get access token by http request
	p := map[string]any{
		"grant_type":    "client_credential",
		"appid":         config.AppId,
		"secret":        config.AppSecret,
		"force_refresh": force,
		//默认使用 false。
		//1. force_refresh = false 时为普通调用模式，access_token 有效期内重复调用该接口不会更新 access_token；
		//2. 当force_refresh = true 时为强制刷新模式，会导致上次获取的 access_token 失效，并返回新的 access_token
	}
	output := new(WxAccessToken)
	if e = api.PostJson(STABLE_ACCESS_TOKEN_URL, nil, p, output); e != nil {
		//glog.Errorf("Get stable access token failed: %v", e)
		return
	}
	at, e = output.ToAccessToken()
	return
}

// https://developers.weixin.qq.com/miniprogram/dev/OpenApiDoc/user-login/code2Session.html
func (wcApi *wcMpApi) Code2Session(config *api.MpConfig, at *api.AccessToken, js_code, anonymous_code string) (acs *api.Code2Session, e error) {
	p := map[string]string{
		"grant_type": "authorization_code",
		"appid":      config.AppId,
		"secret":     config.AppSecret,
		"js_code":    js_code,
	}
	output := new(WxCode2Session)
	if e = api.Get(JSCODE_SESSION_URL, p, output); e != nil {
		//glog.Errorf("code2Session failed: %v", e)
		return
	}
	acs = output.Code2Session
	return

}

// https://developers.weixin.qq.com/miniprogram/dev/OpenApiDoc/user-info/phone-number/getPhoneNumber.html
func (wcApi *wcMpApi) GetPhoneNumber(at *api.AccessToken, code string) (aph *api.PhoneNumber, e error) {
	output := new(WxPhoneNumber)
	if e = api.PostJson(GET_PHONE_NUMBER_URL, map[string]string{
		"access_token": at.AccessToken,
	}, map[string]any{
		"code": code,
	}, output); e != nil {
		//glog.Errorf("Get phone number failed: %v", e)
		return
	}
	aph = output.PhoneInfo
	return

}
